package com.norns.torque.view

import android.bluetooth.BluetoothAdapter
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.gyf.immersionbar.ImmersionBar
import com.hi.dhl.binding.viewbind
import com.norns.torque.BuildConfig
import com.norns.torque.R
import com.norns.torque.bluetooth.BluetoothBroadcastReceiver
import com.norns.torque.bluetooth.ChatServer
import com.norns.torque.databinding.ActivityMainBinding
import com.norns.torque.databinding.ItemMessageBinding
import com.norns.torque.network.NetworkListenerHelper
import com.norns.torque.socket.ClientSocket
import com.norns.torque.utils.AppContext
import java.time.LocalDateTime


class MainActivity : AppCompatActivity() {
    private val binding: ActivityMainBinding by viewbind()
    private var broadcastReceiver: BluetoothBroadcastReceiver?=null
    private var clickCount:Int=0

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase)
        overrideFontScale(newBase)
    }

    /**
     * 重置配置 fontScale：保持字体比例不变，始终为 1.
     */
    private fun overrideFontScale(context: Context?) {
        if (context == null) return
        context.resources.configuration.let {
            it.fontScale = 1f // 保持字体比例不变，始终为 1.
            applyOverrideConfiguration(it) // 应用新的配置
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        ImmersionBar.with(this).statusBarColor(R.color.main)
            .navigationBarColor(R.color.main)
            .autoStatusBarDarkModeEnable(true,0.2f)
            .init()

        // 设置导航栏颜色
       // window.statusBarColor = getColor(R.color.main)
        // 设置状态栏颜色
        //window.navigationBarColor =getColor(R.color.main)
        //setContentView(R.layout.activity_main)
        initView()
        initData()
        subscribeToModel()
    }
    private fun initData(){
        broadcastReceiver = BluetoothBroadcastReceiver()
        val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(broadcastReceiver, filter)
        NetworkListenerHelper.registerNetworkListener(AppContext.context)
    }

    override fun onResume() {
        super.onResume()
        clickCount=0
        ChatServer.disconnect()//断开连接
        ClientSocket.close()
    }


    override fun onDestroy() {
        ChatServer.disconnect()//断开连接
        ClientSocket.close()
        ChatServer.clearMessage()
        unregisterReceiver(broadcastReceiver)
        broadcastReceiver=null
        NetworkListenerHelper.unregisterNetworkCallback(AppContext.context)
        super.onDestroy()
    }

    private fun subscribeToModel() {}

    private fun initView(){
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val localDateTime = LocalDateTime.now()
        val subTitle="版本${BuildConfig.VERSION_NAME}版权所有@${localDateTime.year}诺恩斯工业"
        binding.tvSubTitle.text=subTitle
        binding.tvBluetooth.setOnClickListener {
            startActivity(Intent(this@MainActivity, ScanActivity::class.java))
        }
        binding.tvWifi.setOnClickListener {
            ChatServer.disconnect()
            startActivity(Intent(this@MainActivity, WiFiDeviceActivity::class.java))
        }
        binding.tvRightTitle.setOnClickListener {
            if (clickCount<10){
                clickCount++
            }else{
                if (binding.messageList.visibility== View.GONE){
                    binding.messageList.visibility= View.VISIBLE
                    binding.messageList.models=ChatServer.getMessageList()
                }else{
                    binding.messageList.visibility= View.GONE
                    clickCount=0
                }
            }
        }
//        val dm = resources.displayMetrics
//        val widthPixels = dm.widthPixels
//        val heightPixels = dm.heightPixels
//        Timber.d("宽度：${widthPixels} 高度:${heightPixels}" )

        binding.messageList.linear()
            .setup {
                addType<String>(R.layout.item_message)
                onBind {
                    val binding = getBinding<ItemMessageBinding>() // ViewBinding/DataBinding都支持
                    val message = getModel<String>()
                    binding.tvMessage.text = message
                }
                R.id.tvMessage.onLongClick {
                    val message = getModel<String>()
                    // 获取剪贴板管理器
                    val clipboard: ClipboardManager? = AppContext.context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
                    if (clipboard != null) {
                        // 创建一个剪贴数据对象并设置要复制的文本
                        val clip = ClipData.newPlainText("label", message)
                        // 将剪贴数据对象复制到剪贴板
                        clipboard.setPrimaryClip(clip)
                        // 提示用户复制成功
                        Toast.makeText(applicationContext, "已复制到剪贴板", Toast.LENGTH_SHORT).show()
                    }
                }
            }
    }


}